/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool isSymmetric(TreeNode *root)
    {
        return isSymmetricBfs(root);
        // return isSymmetricRecursive(root->left, root->right);
    }

    bool isSymmetricRecursive(TreeNode *tree1, TreeNode *tree2)
    {
        if (tree1 == nullptr && tree2 == nullptr)
        {
            return true;
        }
        if (((tree1 == nullptr) && (tree2 != nullptr)) || ((tree1 != nullptr) && (tree2 == nullptr)))
        {
            return false;
        }
        if (tree1->val != tree2->val)
        {
            return false;
        }
        return isSymmetricRecursive(tree1->left, tree2->right) && isSymmetricRecursive(tree1->right, tree2->left);
    }

    bool isSymmetricBfs(TreeNode *root)
    {
        vector<TreeNode *> layer1{root->left, root->right};
        vector<TreeNode *> layer2;
        while (true)
        {
            bool allNull = true;
            int n = layer1.size();
            for (int i = 0; i < n / 2; ++i)
            {
                if (layer1[i] == nullptr && layer1[n - 1 - i] == nullptr)
                {
                    continue;
                }
                else if (((layer1[i] == nullptr) && (layer1[n - 1 - i] != nullptr)) || ((layer1[i] != nullptr) && (layer1[n - 1 - i] == nullptr)))
                {
                    return false;
                }
                else
                {
                    if (layer1[i]->val != layer1[n - 1 - i]->val)
                    {
                        return false;
                    }
                    allNull = false;
                }
            }
            if (allNull)
            {
                break;
            }
            for (TreeNode *node : layer1)
            {
                if (node != nullptr)
                {
                    layer2.push_back(node->left);
                    layer2.push_back(node->right);
                }
            }
            layer1.clear();
            layer2.swap(layer1);
        }
        return true;
    }
};